<?php
/**
 * Created by PhpStorm.
 * User: zhanglu
 * Date: 2018/10/18
 * Time: 下午11:32
 */

namespace common\components;

class Upload
{
    public $allowedExts = array("jpeg", "jpg", "png", "pdf", "doc");

    public function uploadfile(){
        // 目录
        $upload_path = getcwd().'/upload/';
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);     // 获取文件后缀名

        if ( in_array($extension, $this->allowedExts) )
        {
            if ($_FILES["file"]["error"] > 0)
            {
                return array(
                    'code' => 201,
                    'msg' => $_FILES["file"]["error"],
                );exit;
            }
            else
            {
                // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
                $new_filename = date('YmdHis') . mt_rand(1000,9999) .'.'. $extension;
                move_uploaded_file($_FILES["file"]["tmp_name"], $upload_path . $new_filename);
                return array(
                    'code' => 200,
                    'data' => '/upload/'. $new_filename,
                    'msg' => 'success',
                );exit;
            }
        }
        else
        {
            return array(
                'code' => 201,
                'msg' => '文件格式不允许',
            );exit;
        }


    }

    public function uploadfilefront(){
        // 目录
        $upload_path = getcwd().'/upload/';
        $upload_path = str_replace('backend', 'frontend', $upload_path);
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);     // 获取文件后缀名

        if ( in_array($extension, $this->allowedExts) )
        {
            if ($_FILES["file"]["error"] > 0)
            {
                return array(
                    'code' => 201,
                    'msg' => $_FILES["file"]["error"],
                );exit;
            }
            else
            {
                // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
                $new_filename = date('YmdHis') . mt_rand(1000,9999) .'.'. $extension;
                move_uploaded_file($_FILES["file"]["tmp_name"], $upload_path . $new_filename);
                return array(
                    'code' => 200,
                    'data' => '/upload/'. $new_filename,
                    'msg' => 'success',
                );exit;
            }
        }
        else
        {
            return array(
                'code' => 201,
                'msg' => '文件格式不允许',
            );exit;
        }


    }


}